//
//  MainSocketDelegate.m
//  TcpTest_Server
//
//  Created by scarlettsun on 12-7-28.
//  Copyright (c) 2012年 tencent. All rights reserved.
//

#import "FileListenSocket.h"
#import "FileSocket.h"
#import "MainWindowController.h"
#import "Buddy.h"
#import "FileTransfer.h"

@implementation FileListenSocket
@synthesize listenSocket;
@synthesize port;

static NSMutableArray *fileSocketsQueue;

+(NSMutableArray *)fileSocketsQueue
{
    if (fileSocketsQueue == nil) {
        fileSocketsQueue = [[NSMutableArray alloc] init];
    }
    return fileSocketsQueue;
}

- (id)init 
{
    socketQueue =dispatch_queue_create("socketQueue", NULL); 
    self.listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
    isRunning = false;
    [self startStop];
    return self;
}

- (void)startStop{
	if(!isRunning)
	{
		NSError *error = nil;
		if(![self.listenSocket acceptOnPort:0 error:&error])
		{
            NSLog(@"Client listen socket 监听失败");
			return;
		}
        ((MainWindowController*)[MainWindowController sharedMainWindowController]).myselfInfo.listenPort = self.listenSocket.localPort;
		NSLog(@"Client listen socket 开始监听 port is %u",self.listenSocket.localPort);
		isRunning = YES; 
	}
	else
	{	
        NSLog(@"Client listen socket 删除重新监听");
		[self.listenSocket disconnect]; 
        [[FileListenSocket fileSocketsQueue] removeAllObjects];
		isRunning = false;
	}
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket;
{	
    FileSocket *fileSocket = [[FileSocket alloc] initWithSock:newSocket];
    FileTransfer *transfer = [[FileTransfer alloc] init];
    [transfer initWithSock:fileSocket];
    [newSocket readDataToLength:LENGTH withTimeout:-1 tag:0];/*has to be set here */
    @synchronized([FileListenSocket fileSocketsQueue])
    {
        [[FileListenSocket fileSocketsQueue] addObject:fileSocket];
    }
    
    NSLog(@"Client FileListenSocket   didAcceptNewSocket\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
{
    NSLog(@"Client FileListenSocket   didConnectToHost\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
{
    NSLog(@"Client FileListenSocket   didWriteDataWithTag\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
{
    NSLog(@"MainSocketDelegate did read sock%@",sock.description);
}

/*- (void)Socket:(GCDAsyncSocket *)sock willDisconnectWithError:(NSError *)err
 {
 NSLog(@"%s %d", __FUNCTION__, __LINE__);
 }*/

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err;
{
    self.listenSocket = nil;
    isRunning = false;
}



@end
